"use client";
import React, { useState } from "react";

interface ImagePreviewProps {
  src: string;
  alt?: string;
  width?: number | string;
  height?: number | string;
  preview?: boolean;
  fallback?: string;
  className?: string;
  style?: React.CSSProperties;
  onPreview?: () => void;
  cover?: React.ReactNode;
}

const ImagePreview: React.FC<ImagePreviewProps> = ({
  src,
  alt = "",
  width,
  height,
  preview = true,
  fallback,
  className = "",
  style,
  onPreview,
  cover,
}) => {
  const [isHovered, setIsHovered] = useState(false);
  const [imageError, setImageError] = useState(false);

  const handleMouseEnter = () => {
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
  };

  const handleImageError = () => {
    setImageError(true);
  };

  const handleClick = () => {
    if (preview && onPreview) {
      onPreview();
    }
  };

  const imageSrc = imageError && fallback ? fallback : src;

  // 默认遮罩内容
  const defaultCover = (
    <div className="flex flex-col items-center justify-center text-white text-center">
      <svg
        className="w-6 h-6 mb-2 text-white"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
        />
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
        />
      </svg>
      <span className="text-sm font-medium">预览</span>
    </div>
  );

  return (
    <div
      className={`relative inline-block cursor-pointer overflow-hidden rounded-lg ${className}`}
      style={{ width, height, ...style }}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      onClick={handleClick}
    >
      <img
        src={imageSrc}
        alt={alt}
    className="block w-full h-full object-cover object-top transition-transform duration-300 ease-in-out hover:scale-105"
        onError={handleImageError}
      />
      {isHovered && (
        <div className="absolute inset-0 bg-black bg-opacity-60 hover:opacity-60 flex items-center justify-center rounded-lg animate-in fade-in duration-200">
          {cover || defaultCover}
        </div>
      )}
    </div>
  );
};

export default ImagePreview;
